package com.vincent.redispractise.part01.serialize;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

/**
 * @Des 测试redistemplate的默认序列化方法
 *      如果redis没有设置序列化方法，将会采用默认的序列化方法，JDK序列化
 * @Date 2022/10/28 14:11
 * @Param  * @param null
 * @Return
 */
@SpringBootTest
public class RedisSerialize {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //测试redisTemplate默认的序列化方式
    @Test
    public void test1(){
        redisTemplate.opsForValue().set("test",new TestObject(20,"vincent"));
        //类型自动转换
        TestObject test = (TestObject)redisTemplate.opsForValue().get("test");
        System.out.println(test);
    }
    @Test
    public void test2(){
        //将java对象手动转换成json字符串
        String json = JSONObject.toJSONString(new TestObject(20, "vincent"));
        stringRedisTemplate.opsForValue().set("sk",json);

        //将json字符串手动转化成java对象
        String jsonStr = stringRedisTemplate.opsForValue().get("sk");
        TestObject test = JSONObject.parseObject(jsonStr, TestObject.class);
        System.out.println(test);

    }

    //使用hutool工具类将对象转化成map
    @Test
    public void test3(){
        TestObject test =new TestObject(20, "vincent");
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(test);
        System.out.println(stringObjectMap);
    }

}
